import { createDiscreteApi } from 'naive-ui'
import { ERROR_NO_TIP_STATUS, ERROR_STATUS } from './config.js'
import { storage } from '@/utils/storage.js'

const { message, loadingBar } = createDiscreteApi(['message', 'dialog', 'notification', 'loadingBar'])

let requestNum = 0

/**
 * @description: 添加loading效果
 * @return {*}
 */
export function addLoading() {
  // 增加loading 如果pending请求数量等于1，弹出loading, 防止重复弹出
  requestNum++
  if (requestNum === 1)
    loadingBar.start()
}

/**
 * @description: 去掉loading效果
 * @return {*}
 */
export function cancelLoading(err = false) {
  // 取消loading 如果pending请求数量等于0，关闭loading
  if (requestNum > 0)
    requestNum--

  if (requestNum === 0)
    err ? loadingBar?.error() : loadingBar?.finish()
}

/**
 * @description: 处理请求成功，但返回后端服务器报错
 * @param {Response} response
 * @return {*}
 */
export function handleResponseError(response) {
  const error = {
    errorType: 'Response Error',
    code: 0,
    message: ERROR_STATUS.default,
    data: null,
  }
  const errorCode = response.status
  const errorMessage = ERROR_STATUS[errorCode] || ERROR_STATUS.default
  Object.assign(error, { code: errorCode, message: errorMessage })

  showError(error)

  return error
}

/**
 * @description: 处理业务错误
 * @param {Record} data 接口返回的后台数据
 * @param {Service} config 后台字段配置
 * @return {*}
 */
export function handleBusinessError(data, config) {
  const { codeKey, msgKey } = config
  const error = {
    errorType: 'Business Error',
    code: data[codeKey],
    message: data[msgKey],
    data: data.data,
  }
  showError(error)

  return error
}

/**
 * @description: 统一成功和失败返回类型
 * @param {any} data
 * @param {boolean} isSuccess
 * @return {*} result
 */
export function handleServiceResult(data, isSuccess = true) {
  const result = {
    isSuccess,
    errorType: null,
    ...data,
  }
  return result
}

/**
 * @description: 处理接口token刷新
 * @return {*}
 */
export async function handleRefreshToken() {
  const isAutoRefresh = import.meta.env.VITE_AUTO_REFRESH_TOKEN === 'Y'
  if (!isAutoRefresh) {
    // 这里可能需要实现登出逻辑
    message.error('登录已过期，请重新登录')
    // 跳转到登录页
    setTimeout(() => {
      window.location.href = '/login'
    }, 1000)
    return
  }

  try {
    // 刷新token
    const response = await fetch('/api/auth/refresh', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ refreshToken: storage.get('refreshToken') }),
    })
    
    if (response.ok) {
      const data = await response.json()
      if (data) {
        storage.set('accessToken', data.accessToken)
        storage.set('refreshToken', data.refreshToken)
        return true
      }
    }
    
    // 刷新失败，退出
    message.error('登录已过期，请重新登录')
    storage.remove('accessToken')
    storage.remove('refreshToken')
    // 跳转到登录页
    setTimeout(() => {
      window.location.href = '/login'
    }, 1000)
    return false
  } catch (error) {
    console.error('刷新token失败:', error)
    message.error('刷新登录状态失败，请重新登录')
    return false
  }
}

export function showError(error) {
  // 如果error不需要提示,则跳过
  const code = Number(error.code)
  if (ERROR_NO_TIP_STATUS.includes(code))
    return

  message.error(error.message)
}